package com.cs171.market.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cs171.market.Repository.CartListRepository;
import com.cs171.market.Repository.OrderRepository;
import com.cs171.market.entity.CartList;
import com.cs171.market.entity.Order;
import com.cs171.market.mapper.CartListMapper;
import com.cs171.market.mapper.CommentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class CartListController {
    @Autowired(required = false)
    private CartListMapper cartListMapper;
    @Autowired
    private CartListRepository cartListRepository;
    /**
     * 6.购物车
     * @return
     */
    @GetMapping("/cartList/{id}")
    public Object SelectByGid(@PathVariable("id")Integer id)
    {
        List<CartList> test = cartListMapper.getCartListByGid(id);
        JSONArray cartListJson=new JSONArray();
        for(CartList each:test)
        {
            cartListJson.add(each.getMessage());
        }

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("success","true");
        JSONObject json=new JSONObject();
        json.put("cartList",cartListJson);
        jsonObject.put("data",json);
        return jsonObject;
    }

    /**
     *
     * @return
     */
    @PostMapping("/cartList/update")
    //更改购物车
    public Object updateCartList(@RequestBody JSONObject jsonParam){
        String act = jsonParam.getString("action");
        String itemId = jsonParam.getString("itemId");
        String norm = jsonParam.getString("norm");
        String value = jsonParam.getString("value");
        Integer userId = 1;
        JSONObject result = new JSONObject();
        Integer itemId1 = Integer.valueOf(itemId);
        CartList cartList = cartListRepository.findById(itemId1).orElse(null);
        if(cartList != null){
            switch (act) {
                case "add":cartListMapper.add(userId, itemId1);break;
                case "minus": {
                    if(cartList.getQuant()>1)
                        cartListMapper.minus(itemId1);
                    else
                        cartListMapper.delete(itemId1);
                }
                    break;
                case "delete":cartListMapper.delete(itemId1);break;
                case "change":cartListMapper.change(itemId1,Integer.valueOf(value));break;
            }
            result.put("code",200);
            return result;
        }
        else {
            if (act.equals("add")) {
                cartListMapper.addItem(userId, itemId1, norm);
                result.put("code", 200);
                return result;
            }
            else
            result.put("error", "购物车修改出错");
            result.put("code", 500);
            return result;
        }
    }
}
